home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / tokenize.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-29  |  12KB  |  359 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Tokenization help for Python programs.
  5.  
  6. generate_tokens(readline) is a generator that breaks a stream of
  7. text into Python tokens.  It accepts a readline-like method which is called
  8. repeatedly to get the next line of input (or "" for EOF).  It generates
  9. 5-tuples with these members:
  10.  
  11.     the token type (see token.py)
  12.     the token (a string)
  13.     the starting (row, column) indices of the token (a 2-tuple of ints)
  14.     the ending (row, column) indices of the token (a 2-tuple of ints)
  15.     the original line (string)
  16.  
  17. It is designed to match the working of the Python tokenizer exactly, except
  18. that it produces COMMENT tokens for comments and gives type OP for all
  19. operators
  20.  
  21. Older entry points
  22.     tokenize_loop(readline, tokeneater)
  23.     tokenize(readline, tokeneater=printtoken)
  24. are the same, except instead of generating tokens, tokeneater is a callback
  25. function to which the 5 fields described above are passed as 5 arguments,
  26. each time a new token is found.'''
  27. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  28. __credits__ = 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
  29. import string
  30. import re
  31. from token import *
  32. import token
  33. __all__ = _[1] + [
  34.     'COMMENT',
  35.     'tokenize',
  36.     'generate_tokens',
  37.     'NL',
  38.     'untokenize']
  39. del x
  40. del token
  41. COMMENT = N_TOKENS
  42. tok_name[COMMENT] = 'COMMENT'
  43. NL = N_TOKENS + 1
  44. tok_name[NL] = 'NL'
  45. N_TOKENS += 2
  46.  
  47. def group(*choices):
  48.     return '(' + '|'.join(choices) + ')'
  49.  
  50.  
  51. def any(*choices):
  52.     return group(*choices) + '*'
  53.  
  54.  
  55. def maybe(*choices):
  56.     return group(*choices) + '?'
  57.  
  58. Whitespace = '[ \\f\\t]*'
  59. Comment = '#[^\\r\\n]*'
  60. Ignore = Whitespace + any('\\\\\\r?\\n' + Whitespace) + maybe(Comment)
  61. Name = '[a-zA-Z_]\\w*'
  62. Hexnumber = '0[xX][\\da-fA-F]*[lL]?'
  63. Octnumber = '0[0-7]*[lL]?'
  64. Decnumber = '[1-9]\\d*[lL]?'
  65. Intnumber = group(Hexnumber, Octnumber, Decnumber)
  66. Exponent = '[eE][-+]?\\d+'
  67. Pointfloat = group('\\d+\\.\\d*', '\\.\\d+') + maybe(Exponent)
  68. Expfloat = '\\d+' + Exponent
  69. Floatnumber = group(Pointfloat, Expfloat)
  70. Imagnumber = group('\\d+[jJ]', Floatnumber + '[jJ]')
  71. Number = group(Imagnumber, Floatnumber, Intnumber)
  72. Single = "[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"
  73. Double = '[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'
  74. Single3 = "[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''"
  75. Double3 = '[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
  76. Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""')
  77. String = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'", '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*"')
  78. Operator = group('\\*\\*=?', '>>=?', '<<=?', '<>', '!=', '//=?', '[+\\-*/%&|^=<>]=?', '~')
  79. Bracket = '[][(){}]'
  80. Special = group('\\r?\\n', '[:;.,`@]')
  81. Funny = group(Operator, Bracket, Special)
  82. PlainToken = group(Number, Funny, String, Name)
  83. Token = Ignore + PlainToken
  84. ContStr = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*" + group("'", '\\\\\\r?\\n'), '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*' + group('"', '\\\\\\r?\\n'))
  85. PseudoExtras = group('\\\\\\r?\\n', Comment, Triple)
  86. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  87. (tokenprog, pseudoprog, single3prog, double3prog) = map(re.compile, (Token, PseudoToken, Single3, Double3))
  88. endprogs = {
  89.     "'": re.compile(Single),
  90.     '"': re.compile(Double),
  91.     "'''": single3prog,
  92.     '"""': double3prog,
  93.     "r'''": single3prog,
  94.     'r"""': double3prog,
  95.     "u'''": single3prog,
  96.     'u"""': double3prog,
  97.     "ur'''": single3prog,
  98.     'ur"""': double3prog,
  99.     "R'''": single3prog,
  100.     'R"""': double3prog,
  101.     "U'''": single3prog,
  102.     'U"""': double3prog,
  103.     "uR'''": single3prog,
  104.     'uR"""': double3prog,
  105.     "Ur'''": single3prog,
  106.     'Ur"""': double3prog,
  107.     "UR'''": single3prog,
  108.     'UR"""': double3prog,
  109.     'r': None,
  110.     'R': None,
  111.     'u': None,
  112.     'U': None }
  113. triple_quoted = { }
  114. for t in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""'):
  115.     triple_quoted[t] = t
  116.  
  117. single_quoted = { }
  118. for t in ("'", '"', "r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"', "ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"'):
  119.     single_quoted[t] = t
  120.  
  121. tabsize = 8
  122.  
  123. class TokenError(Exception):
  124.     pass
  125.  
  126.  
  127. class StopTokenizing(Exception):
  128.     pass
  129.  
  130.  
  131. def printtoken(type, token, .2, .3, line):
  132.     (srow, scol) = .2
  133.     (erow, ecol) = .3
  134.     print '%d,%d-%d,%d:\t%s\t%s' % (srow, scol, erow, ecol, tok_name[type], repr(token))
  135.  
  136.  
  137. def tokenize(readline, tokeneater = printtoken):
  138.     '''
  139.     The tokenize() function accepts two parameters: one representing the
  140.     input stream, and one providing an output mechanism for tokenize().
  141.  
  142.     The first parameter, readline, must be a callable object which provides
  143.     the same interface as the readline() method of built-in file objects.
  144.     Each call to the function should return one line of input as a string.
  145.  
  146.     The second parameter, tokeneater, must also be a callable object. It is
  147.     called once for each token, with five arguments, corresponding to the
  148.     tuples generated by generate_tokens().
  149.     '''
  150.     
  151.     try:
  152.         tokenize_loop(readline, tokeneater)
  153.     except StopTokenizing:
  154.         pass
  155.  
  156.  
  157.  
  158. def tokenize_loop(readline, tokeneater):
  159.     for token_info in generate_tokens(readline):
  160.         tokeneater(*token_info)
  161.     
  162.  
  163.  
  164. def untokenize(iterable):
  165.     '''Transform tokens back into Python source code.
  166.  
  167.     Each element returned by the iterable must be a token sequence
  168.     with at least two elements, a token number and token value.
  169.  
  170.     Round-trip invariant:
  171.         # Output text will tokenize the back to the input
  172.         t1 = [tok[:2] for tok in generate_tokens(f.readline)]
  173.         newcode = untokenize(t1)
  174.         readline = iter(newcode.splitlines(1)).next
  175.         t2 = [tok[:2] for tok in generate_tokens(readline)]
  176.         assert t1 == t2
  177.     '''
  178.     startline = False
  179.     prevstring = False
  180.     indents = []
  181.     toks = []
  182.     toks_append = toks.append
  183.     for tok in iterable:
  184.         (toknum, tokval) = tok[:2]
  185.         if toknum in (NAME, NUMBER):
  186.             tokval += ' '
  187.         
  188.         if toknum == STRING:
  189.             if prevstring:
  190.                 tokval = ' ' + tokval
  191.             
  192.             prevstring = True
  193.         else:
  194.             prevstring = False
  195.         if toknum == INDENT:
  196.             indents.append(tokval)
  197.             continue
  198.         elif toknum == DEDENT:
  199.             indents.pop()
  200.             continue
  201.         elif toknum in (NEWLINE, COMMENT, NL):
  202.             startline = True
  203.         elif startline and indents:
  204.             toks_append(indents[-1])
  205.             startline = False
  206.         
  207.         toks_append(tokval)
  208.     
  209.     return ''.join(toks)
  210.  
  211.  
  212. def generate_tokens(readline):
  213.     '''
  214.     The generate_tokens() generator requires one argment, readline, which
  215.     must be a callable object which provides the same interface as the
  216.     readline() method of built-in file objects. Each call to the function
  217.     should return one line of input as a string.  Alternately, readline
  218.     can be a callable function terminating with StopIteration:
  219.         readline = open(myfile).next    # Example of alternate readline
  220.  
  221.     The generator produces 5-tuples with these members: the token type; the
  222.     token string; a 2-tuple (srow, scol) of ints specifying the row and
  223.     column where the token begins in the source; a 2-tuple (erow, ecol) of
  224.     ints specifying the row and column where the token ends in the source;
  225.     and the line on which the token was found. The line passed is the
  226.     logical line; continuation lines are included.
  227.     '''
  228.     lnum = parenlev = continued = 0
  229.     namechars = string.ascii_letters + '_'
  230.     numchars = '0123456789'
  231.     (contstr, needcont) = ('', 0)
  232.     contline = None
  233.     indents = [
  234.         0]
  235.     while None:
  236.         
  237.         try:
  238.             line = readline()
  239.         except StopIteration:
  240.             line = ''
  241.  
  242.         lnum = lnum + 1
  243.         pos = 0
  244.         max = len(line)
  245.         if contstr:
  246.             if not line:
  247.                 raise TokenError, ('EOF in multi-line string', strstart)
  248.             
  249.             endmatch = endprog.match(line)
  250.             if endmatch:
  251.                 pos = end = endmatch.end(0)
  252.                 yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line)
  253.                 (contstr, needcont) = ('', 0)
  254.                 contline = None
  255.             elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  256.                 yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline)
  257.                 contstr = ''
  258.                 contline = None
  259.                 continue
  260.             else:
  261.                 contstr = contstr + line
  262.                 contline = contline + line
  263.         elif parenlev == 0 and not continued:
  264.             if not line:
  265.                 break
  266.             
  267.             column = 0
  268.             while pos < max:
  269.                 if line[pos] == ' ':
  270.                     column = column + 1
  271.                 elif line[pos] == '\t':
  272.                     column = (column / tabsize + 1) * tabsize
  273.                 elif line[pos] == '\x0c':
  274.                     column = 0
  275.                 else:
  276.                     break
  277.                 pos = pos + 1
  278.             if pos == max:
  279.                 break
  280.             
  281.             if line[pos] in '#\r\n':
  282.                 yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line)
  283.                 continue
  284.             
  285.             if column > indents[-1]:
  286.                 indents.append(column)
  287.                 yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  288.             
  289.             while column < indents[-1]:
  290.                 if column not in indents:
  291.                     raise IndentationError('unindent does not match any outer indentation level', ('<tokenize>', lnum, pos, line))
  292.                 
  293.                 indents = indents[:-1]
  294.                 yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
  295.         elif not line:
  296.             raise TokenError, ('EOF in multi-line statement', (lnum, 0))
  297.         
  298.         continued = 0
  299.         while pos < max:
  300.             pseudomatch = pseudoprog.match(line, pos)
  301.             if pseudomatch:
  302.                 (start, end) = pseudomatch.span(1)
  303.                 spos = (lnum, start)
  304.                 epos = (lnum, end)
  305.                 pos = end
  306.                 token = line[start:end]
  307.                 initial = line[start]
  308.                 if (initial in numchars or initial == '.') and token != '.':
  309.                     yield (NUMBER, token, spos, epos, line)
  310.                 elif initial in '\r\n':
  311.                     if not parenlev > 0 or NL:
  312.                         pass
  313.                     yield (NEWLINE, token, spos, epos, line)
  314.                 elif initial == '#':
  315.                     yield (COMMENT, token, spos, epos, line)
  316.                 elif token in triple_quoted:
  317.                     endprog = endprogs[token]
  318.                     endmatch = endprog.match(line, pos)
  319.                     if endmatch:
  320.                         pos = endmatch.end(0)
  321.                         token = line[start:pos]
  322.                         yield (STRING, token, spos, (lnum, pos), line)
  323.                     else:
  324.                         strstart = (lnum, start)
  325.                         contstr = line[start:]
  326.                         contline = line
  327.                         break
  328.                 elif initial in single_quoted and token[:2] in single_quoted or token[:3] in single_quoted:
  329.                     if token[-1] == '\n':
  330.                         strstart = (lnum, start)
  331.                         if not endprogs[initial] and endprogs[token[1]]:
  332.                             pass
  333.                         endprog = endprogs[token[2]]
  334.                         contstr = line[start:]
  335.                         needcont = 1
  336.                         contline = line
  337.                         break
  338.                     else:
  339.                         yield (STRING, token, spos, epos, line)
  340.                 elif initial in namechars:
  341.                     yield (NAME, token, spos, epos, line)
  342.                 elif initial == '\\':
  343.                     continued = 1
  344.                 elif initial in '([{':
  345.                     parenlev = parenlev + 1
  346.                 elif initial in ')]}':
  347.                     parenlev = parenlev - 1
  348.                 
  349.                 yield (OP, token, spos, epos, line)
  350.                 continue
  351.             yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line)
  352.             pos = pos + 1
  353.         continue
  354.         for indent in indents[1:]:
  355.             yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
  356.         
  357.     yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  358.  
  359.